package com.example.teachdemo4;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.example.teachdemo4.model.MyWeather;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetworkJsonDataActivity extends AppCompatActivity {
    //网站：https://jx.gdgm.cn:443/skills/wv/38767871
    TextView tv_content;
    Handler handler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_network_json_data);
        tv_content = findViewById(R.id.tv_content);

        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0x1100){
                    String result = msg.obj.toString();
                    Gson gson = new Gson();
                    MyWeather weather = gson.fromJson(result,MyWeather.class);
                    tv_content.setText(weather.getWeatherinfo().getCity());
                }
            }
        };

    }
    public void getData(View view) {


        new Thread(new Runnable() {
            @Override
            public void run() {

                URL url = null;
                HttpURLConnection connection = null;
                InputStreamReader streamReader = null;
                BufferedReader reader = null;
                try{

                    url = new URL("http://www.weather.com.cn/data/sk/101010100.html");

                    connection = (HttpURLConnection) url.openConnection();

                    streamReader = new InputStreamReader(connection.getInputStream());

                    reader = new BufferedReader(streamReader);

                    String result = "";
                    String line = "";

                    while ((line = reader.readLine()) != null){
                        result += line;

                    }
                    Log.v("msg",result);
                    reader.close();
                    Message message = new Message();
                    message.what = 0x1100;
                    message.obj = result;

                    handler.sendMessage(message);

                }catch (Exception e){
                    Log.v("msg",e.getMessage());
                }
            }
        }).start();
    }
}
